package com.mo.json;

import com.alibaba.fastjson.serializer.BigDecimalCodec;
import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.ObjectSerializer;
import com.alibaba.fastjson.serializer.SerializeConfig;

import java.io.IOException;
import java.lang.reflect.Type;
import java.math.BigDecimal;
import java.util.function.Function;

/**
 * BigDecimal自定义序列化
 *
 * @author moon.pan
 * @program mo-all
 * @apiNote
 * @since 2022/3/29
 */
public class BigDecimalSerializer extends BigDecimalCodec {

    public Function<BigDecimal, Object> handler;

    public BigDecimalSerializer(Function<BigDecimal, Object> handler) {
        this.handler = handler;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object instanceof BigDecimal) {
            object = handler.apply((BigDecimal) object);
        }

        if( object instanceof BigDecimal){
            super.write(serializer, object, fieldName, fieldType, features);
        }else {
            Class<?> objectClass = object.getClass();
            SerializeConfig config = serializer.getMapping();
            ObjectSerializer objectWriter = config.getObjectWriter(objectClass);
            objectWriter.write(serializer, object, fieldName, fieldType, features);
        }
    }
}
